package com.lancabbage.gorgeous.controller.project;

import com.lancabbage.gorgeous.bean.dto.ApiInfoDto;
import com.lancabbage.gorgeous.bean.dto.ProjectBranchAddDto;
import com.lancabbage.gorgeous.bean.dto.ProjectBranchDto;
import com.lancabbage.gorgeous.bean.po.Project;
import com.lancabbage.gorgeous.bean.po.ProjectBranch;
import com.lancabbage.gorgeous.bean.vo.base.BaseResponse;
import com.lancabbage.gorgeous.bean.vo.project.ProjectBranchAddVo;
import com.lancabbage.gorgeous.bean.vo.project.ProjectBranchVo;
import com.lancabbage.gorgeous.enums.ApiTypeEnum;
import com.lancabbage.gorgeous.map.PoToVo;
import com.lancabbage.gorgeous.service.ApiInfoService;
import com.lancabbage.gorgeous.service.ProjectBranchService;
import com.lancabbage.gorgeous.service.ProjectService;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: lanyanhua
 * @date: 2020/12/5 6:35 下午
 * @Description: 项目分支
 */
@RestController
@RequestMapping("/branch")
public class ProjectBranchController {

    private final ProjectBranchService branchService;
    private final ProjectService projectService;
    private final ApiInfoService apiInfoService;

    public ProjectBranchController(ProjectBranchService branchService, ProjectService projectService, ApiInfoService apiInfoService) {
        this.branchService = branchService;
        this.projectService = projectService;
        this.apiInfoService = apiInfoService;
    }

    /**
     * 添加项目分支
     */
    @PostMapping("/addProjectBranch")
    public BaseResponse<Integer> addProjectBranch(@RequestBody @Valid ProjectBranchAddVo vo) {
        ProjectBranchAddDto dto = new ProjectBranchAddDto();
        dto.setName(vo.getName());
        Project project = projectService.getProjectById(vo.getProjectId());
        Assert.notNull(project, "项目ID不存在");
        dto.setProject(project);
        // git信息 项目名
        int id = branchService.addProjectBranch(dto);
        return BaseResponse.successInstance(id);
    }

    /**
     * 拉git代码
     *
     * @param projectId 项目ID
     * @param branchId  分支ID
     */
    @PostMapping("/pullProjectBranch")
    public BaseResponse<String> pullProjectBranch(@RequestParam Integer projectId, @RequestParam Integer branchId) {
        Project project = projectService.getProjectById(projectId);
        Assert.notNull(project, "项目ID不存在");
        ProjectBranchDto branch = new ProjectBranchDto();
        branch.setProject(project);
        branch.setId(branchId);
        // git信息 项目名
        branchService.pullProjectBranch(branch);
        return BaseResponse.successInstance("成功");
    }

    /**
     * 删除分支
     *
     * @param id 分支ID
     */
    @DeleteMapping("/deleteBranchById")
    public BaseResponse<String> deleteBranchById(@RequestParam Integer id) {
        int count = branchService.countBranch(id);
        Assert.isTrue(count > 1, "最后一个分支不能删除，可以选择删除项目");
        //删除分支 判断当前分支是否被引用 =》 选择替换分支
        if (branchService.isReferenced(id)) {
            return BaseResponse.errorInstance(50001, "当前分支API被引用");
        }
        branchService.deleteBranchById(id);
        return BaseResponse.successInstance("成功");
    }

    /**
     * 项目分支列表
     *
     * @param projectId 项目ID
     * @return 分支列表
     */
    @GetMapping("/listBranchByProjectId")
    public BaseResponse<List<ProjectBranchVo>> listBranchByProjectId(@RequestParam("projectId") Integer projectId) {
        List<ProjectBranch> list = branchService.listBranchByProjectId(projectId);
        List<ProjectBranchVo> voList = PoToVo.INSTANCE.listProjectBranchVo(list);
        return BaseResponse.successInstance(voList);
    }

    /**
     * 更换分支
     *
     * @param sourceId 源分支ID
     * @param targetId 目标分支ID
     * @param type     0:正常，1:合并缺少的API不删除，2:使用目标分支缺少的菜单删除 停用感觉太复杂了，目标分支必须包含当前分支所有API
     */
    @PutMapping("/replaceBranch/{sourceId}/{targetId}")
    public BaseResponse<String> replaceBranch(@PathVariable("sourceId") Integer sourceId
            , @PathVariable("targetId") Integer targetId, Integer type) {
        //查询被使用接口
        List<ApiInfoDto> apiList = apiInfoService.listReferencedApiByBranchId(sourceId, targetId);
//        if(type== 0) {
        List<ApiInfoDto> collect = apiList.stream().filter(i -> i.getTargetId() == null).collect(Collectors.toList());
        if (!collect.isEmpty()) {
            return BaseResponse.errorInstance(50001, "目标分支缺少API,请检测分支是否合并\n" + collect.stream()
                    .map(i -> i.getName() + "\t" + ApiTypeEnum.getDescByCode(i.getType())
                            + "\t" + i.getPath()).collect(Collectors.joining("\n")));
        }
//        }
        branchService.replaceBranch(apiList, type);
        return BaseResponse.successInstance("更换成功");
    }
}
